package jjoms.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jjoms.model.item.MessageVO;
import jjoms.model.member.MemberService;
import jjoms.model.member.MemberVO;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/member")
public class MemberController {
   @Resource(name = "memberServiceImpl")
   private MemberService memberService;
   
   //홈으로 가는 메서드- getRank.moja로 들려 검색어순위, 다운로드 상품 순위를 가지고 홈으로 간다.
   @RequestMapping("/home.moja")
   public String home(){
      //System.out.println("home");
      return "redirect:/report/getRank.moja";
   }
   
   //로그인하는 메서드
   //로그인이 되면 home.moja메서드로 페이지 이동
   //로그인 실패하면 login_fail.jsp로 페이지 이동
   @RequestMapping(value = "/login.moja", method = RequestMethod.POST)
   public String login(HttpSession session, MemberVO vo) {
	   System.out.println(vo.getMemberId());
		MemberVO rvo = memberService.login(vo);
		System.out.println(rvo);
		String returnVal = null;
		if (rvo != null) {
			session.setAttribute("mvo", rvo);
			returnVal = "redirect:/member/home.moja";
		}else{
			returnVal = "login_fail.member";
		}
		return returnVal;
	}

   	//로그아웃 한뒤 home.moja 메서드로 리다이렉트
	@RequestMapping("/logout.moja")
	public String logout(HttpSession session, HttpServletRequest request) {
		session = request.getSession(false);
		if (session != null)
			session.invalidate();
		return "redirect:/member/home.moja";
	}

	//당신은 누구인가요??
	//자동으로 맵핑
	@RequestMapping("/{viewId}_view.moja")
	public String showView(@PathVariable("viewId") String viewId) {
		System.out.println("showView : " + viewId);
		return viewId + "_view.member";
	}
	
	@RequestMapping("/findIdandPassword.moja")
	public String findIdandPassword(){
		System.out.println("findIdandPassword");
		return "/member/findIdandPassword";
	}

	//AJAX로 아이디 체크후 체크 결과를 리턴
	@RequestMapping("/idcheckAjax.moja")
	@ResponseBody
	public int idcheckAjax(String memberId) {
		System.out.println(memberId);
		return memberService.idcheck(memberId);

	}

	@RequestMapping(value = "/register.moja", method = RequestMethod.POST)
	public String register(MemberVO vo) throws UnsupportedEncodingException {
		System.out.println("registercontroller:" + vo.getMemberId());
		System.out.println(vo);
		System.out.println("memberGender : " + vo.getMemberGender());
		memberService.registerMember(vo);

		String memberId = URLEncoder.encode(vo.getMemberId(), "utf-8");
		return "redirect:registerResultView.moja?memberId=" + memberId;
	}

	@RequestMapping("/registerResultView.moja")
	public ModelAndView registerResultView(String memberId)
			throws UnsupportedEncodingException {
		// redirect 방식 한글처리
		System.out.println(memberId);
		memberId = URLDecoder.decode(memberId, "utf-8");
		MemberVO vo = memberService.findMemberById(memberId);
		System.out.println(vo);
		return new ModelAndView("register_result.member", "mvo", vo);
	}

	@RequestMapping(value = "/auth_updateMember.moja", method = RequestMethod.POST)
	public String updateMember(HttpServletRequest request, MemberVO pvo) {
		HttpSession session = request.getSession(false);

		System.out.println("update!");
		memberService.updateMember(pvo);
		session.setAttribute("mvo", pvo);
		String path = "redirect:update_result.moja";

		return path;
	}

	@RequestMapping("/update_result.moja")
	public String updateResult() {
		return "update_result.member";
	}

	@RequestMapping("/auth_manager_memberList.moja")
	public ModelAndView getAllMemberList() {
		ArrayList<MemberVO> list = (ArrayList<MemberVO>) memberService.getAllMemberList();
		System.out.println("모든멤버 출력"+list);
		return new ModelAndView("manager_memberList.member", "mlist", list);
	}

	@RequestMapping("/auth_manager_showMemberContent.moja")
	public ModelAndView showMemberContent(String memberId) {
		System.out.println(memberId);
		MemberVO vo = memberService.findMemberById(memberId);
		return new ModelAndView("manager_showMemberContent.member", "mvo", vo);
	}

	@RequestMapping("/auth_manager_deleteMember.moja")
	public String deleteMember(String memberId) {
		memberService.deleteMember(memberId);
		return "redirect:manager_memberList.moja";
	}

	@RequestMapping("/auth_manager_updateMemberView.moja")
	public ModelAndView updateMemberView(String memberId) {
		MemberVO vo = memberService.findMemberById(memberId);
		return new ModelAndView("manager_updateMemberView.member", "mvo", vo);
	}

	@RequestMapping("/auth_manager_updateMember.moja")
	public String updateMember(MemberVO vo) {
		memberService.updateMember(vo);
		return "redirect:auth_manager_memberList.moja";
	}

	@RequestMapping("/findId.moja")
	@ResponseBody
	public String findId(String memberName, String phone){
		System.out.println("id찾기:" + memberName);
		System.out.println("id찾기 : " + phone);
		String memberId = memberService.findId(memberName, phone);
		System.out.println("찾은 ID = "+ memberId);
		if (memberId == null) {
			return null;
		} else {
			return memberId;
		}
	}

	@RequestMapping("/findPassword.moja")
	@ResponseBody
	public String findPassword(String memberId1) {
		// System.out.println("adsfads:"+memberId1);
		MemberVO vo = memberService.findPassword(memberId1);
		// System.out.println("비번:"+vo.getMemberPassword());
		if (vo == null) {
			return null;
		} else {
			return vo.getMemberPassword();
		}

	}

	@RequestMapping("/reChargeMoneyPrice.moja")
	@ResponseBody
	public int reChargeMoneyPrice(int memberMoney) {
		int count = 0;
		System.out.println(memberMoney);

		count = memberService.moneyWithTax(memberMoney);

		return count;
	}

	@RequestMapping("/reChargeMoneyPrice1.moja")
	@ResponseBody
	public int reChargeMoneyPrice1(int memberMoneyText) {
		int count = 0;
		System.out.println(memberMoneyText);
		count = memberService.moneyWithTax(memberMoneyText);
		return count;
	}

	@RequestMapping("/updateRecharge.moja")
	public String updateRecharge(String memberId, int result1,
			HttpServletRequest request) {
		System.out.println("컨트롤러 충전아이디:" + memberId);
		System.out.println("컨트롤러 충전금액:" + result1);
		memberService.updateMemberMoney(memberId, result1);
		MemberVO mvo = memberService.findMemberById(memberId);
		HttpSession session = request.getSession(false);
		session.setAttribute("mvo", mvo);
		return "redirect:payment_view.moja";
	}

	@RequestMapping("/getAllManager.moja")
	@ResponseBody
	public List<String> getAllManager() {
		return memberService.getAllManagerList();
	}

	@RequestMapping("/auth_manager_ajaxdeleteMember.moja")
	@ResponseBody
	public List<MemberVO> auth_manager_ajaxdeleteMember(String memberId) {
		System.out.println("memberId" + memberId);
		memberService.deleteMember(memberId);
		return memberService.getAllMemberList();
	}

	/**
	 * 승인요청들어온 member SellAuthority = 'middle' update
	 */
	@RequestMapping("/sellRequest.moja")
	public String sellRequest(HttpSession session,HttpServletRequest request,String memberId) {
		System.out.println("sellRequest : " + memberId);
		memberService.updateSellAuthority(memberId);
		session = request.getSession(false);
		MemberVO mvo = (MemberVO) session.getAttribute("mvo");
		mvo.setMemberSellAuthority("middle");
		System.out.println("middle"+mvo);
		session.setAttribute("mvo", mvo);
		return "redirect:/member/home.moja";
	}

	@RequestMapping("/auth_manager_passAuthorityMember.moja")
	@ResponseBody
	public String auth_manager_passAuthorityMember(String memberId) {
		System.out.println("memberId" + memberId);
		memberService.passAuthorityMember(memberId);
		return "pass";
	}

	@RequestMapping("/getMessageBySender.moja")
	@ResponseBody
	public ArrayList<MessageVO> getMessageBySender(HttpSession session,
			HttpServletRequest request) {
		session = request.getSession(false);
		MemberVO vo = (MemberVO) session.getAttribute("mvo");
		String memberId = vo.getMemberId();
		ArrayList<MessageVO> list = (ArrayList<MessageVO>) memberService.getMessageBySender(memberId);
		return list;
	}
	@RequestMapping("/getMessageByReceiver.moja")
	@ResponseBody
	public ArrayList<MessageVO> getMessageByReceiver(HttpSession session,
			HttpServletRequest request) {
		session = request.getSession(false);
		MemberVO vo = (MemberVO) session.getAttribute("mvo");
		String memberId = vo.getMemberId();
		ArrayList<MessageVO> list = (ArrayList<MessageVO>) memberService.getMessageByReceiver(memberId);
		return list;
	}
	@RequestMapping("/deleteSender.moja")
	public String deleteSender(int messageNo){
		memberService.deleteSender(messageNo);
		
		return "redirect:messageStorage_view.moja";
	}
	@RequestMapping("/deleteRecevier.moja")
	public String deleteReceiver(int messageNo){
		memberService.deleteReceiver(messageNo);
		
		return "redirect:messageStorage_view.moja";
	}
}
